<!--author:shanwj,date:2017/10/25 -->
<template>
    <div class="bos-file-uplader-component-container" :class="{'comp-upload-successFile': compUploadSuccessFile, 
    'img-type-upload': upFileType=='image'}">
        <el-upload
            ref="upload"
            :action="FileUploadUrl"
            :before-upload="handleBeforeUp"
            :on-progress="handleProgress"
            :on-success="handleSuccess"
            :on-remove="handleRemove"
            :on-error="handleError"
            :show-file-list="fileListShow"
            :disabled="disabled"
            :accept="acceptList"
            :drag="isDrag"
            :multiple="isMultiple"
            :file-list="fileList"
            :list-type="listType"
            :on-change="handleChange"
            :auto-upload="isAuto"
            :on-preview="handlePreview"
        >
        <slot>
            <!-- 默认传的值需要手动写入 -->
            <!-- <div class="up-container el-upload">
                <i class="el-icon-plus"></i>
            </div> -->
        </slot>
        <slot name="trigger"></slot>
        </el-upload>
        <div class="upload-again" slot="trigger" @click="uploadAgain" v-show="compUploadSuccessFile">重新上传</div>
        <!-- 提示信息 -->
        <div class="tips">
            <slot name="tip"></slot>
        </div>
        <!-- 上传提示 -->
        <el-dialog v-model="dialogVisible" size="tiny" custom-class="dialog-layer">
            <img :src="dialogImageUrl" width="100%" alt="">
        </el-dialog>
    </div>
</template>
<script>
// 文件上传测试地址 http://123.206.189.55:28810/cos/upload
// 文件上传的正式服地址 http://dfs.upload1.jzexueyun.com/cos/upload
var IMG_MAXSIZE = 5; // 上传图片最大是5M
const FILE_MAXSIZE = 100; // 上传文件最大是100M
const VIDEO_MAXSIZE = 500; // 视频文件上传最大是20M
const IMG_REGEXP = /^image\/(gif|jpe?g|png|GIF|JPG|PNG)$/;  
// const IMG_REGEXP = /\.(gif|jpg|png|GIF|JPG|PNG)$/;  
const FILE_REGEXP = /\.(doc|docx|xlsx|xls|zip|rar|ppt|pptx|pdf|txt)$/;
const FILE_EXCEL_REGEXP = /\.(xlsx|xls)$/; 
const FILE_EXCEL = ['application/vnd.ms-excel', 'application/x-xls', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
const FILE_DOCX = ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/msword'];
// const FILE_VIDEO = /\.(mp4|flv|rm|avi|rmvb)$/;
const FILE_VIDEO = /\.(mp4|MP4)$/;
export default {
    name: 'FileUpload',
    props: {
        // 是否支持拖拽上传
        isDrag: {
            type: Boolean,
            default: false
        },
        // 单文件多文件上传默认单文件
        isMultiple: {
            type: Boolean,
            default: false
        },
        // 上传图片还是文档默认上传图片
        upFileType: {
            type: String,
            default: 'image'
        },
        // 禁用上传
        disabled: {
            type: Boolean,
            default: false
        },
        isAuto: {
            type: Boolean,
            default: true
        },
        // 上传文件列表
        fileList: {
            type: Array,
            default() {
                return [];
            }
        },
        // 上传文件列表展示类型
        // listType: {
        //     type: String,
        //     default: 'text'
        // },
        // 是否显示上传文件列表
        fileListShow: {
            type: Boolean,
            default: false
        },
        // isListen: {
        //     type: Boolean,
        //     default: false
        // }
        imgSize: {
            type: Number,
            default: 0
        }
    },
    computed: {
        acceptList() {
            var accept = '';
            if (this.upFileType=='image') {
                accept = '.jpg,.png,.gif,.jpeg';
            }
            if (this.upFileType=='file') {
                accept = '.doc,.docx,.xlsx,.xls,.ppt,.rar,.zip,.pptx,.pdf,.txt';
            }
            if (this.upFileType=='excel') {
                accept = '.xlsx,.xls';
            }
            if (this.upFileType=='docx') {
                accept = '.docx,.doc';
            }
            if (this.upFileType=='video') {
                // accept = '.mp4,.flv,.rm,.avi,.rmvb';
                accept = '.mp4';
            }
            return accept;
        },
        isBackIn() {
            return this.fileList.length;
        },
        listType() {
            if (this.upFileType=='image') {
                return 'picture-card';
            } else {
                return 'text';
            }
        }
    },
    data() {
        return {
            dialogVisible: false,
            curFileUrl: '', // 当前上传的文件
            dialogImageUrl: '',
            compUploadSuccessFile: false,
            responseJson: {
                fileName: ''
            },
            FileUploadUrl: process.env.UPLOAD_URL,
            success: false
            // uploadUrl:UPLOAD_URL
        }
    },
    watch: {
        fileList(val, oldVal) {
            if (val.length > 0) {
                // (this.upFileType =='image')&&(this.compUploadSuccessFile = true);
            }
        }
    },
    created() {
        // console.log(process.env.UPLOAD_URL,'0000000')
        if (this.fileList&&this.fileList.length) {
            this.curFileUrl = this.fileList[0];
        }
        if (this.imgSize) {
            IMG_MAXSIZE = this.imgSize;
            IMG_MAXSIZE = IMG_MAXSIZE >= 20 ? 20 : IMG_MAXSIZE;
        }
    },
    methods: {
        // 清空上传的文件
        clearFiles() {
            this.$refs.upload.clearFiles();
            this.curFileUrl = '';
            this.compUploadSuccessFile = false;
        },
        // 上传前处理的事件
        handleBeforeUp(file) {
            var unType = '';
            // 如果上传的是图片|xlxs文件的格式的话 file.type 类型判断
            if (this.upFileType == 'image' || this.upFileType === 'excel' || this.upFileType == 'docx') {
                unType = this._getFileType(file.type, file.name); // 判断上传文件的类型
            } else {
                unType = this._getFileType(file.name); // 判断上传文件的类型
            } 
            if (!unType) return false;
            let upSize = this._getFileSize(file.size);
            if (this.upFileType === 'image') {
                if (upSize > IMG_MAXSIZE) {
                    // this.$emit('update:fileListShow', false);
                    console.log(this.fileList, 'fileList');
                    this.$emit('update:fileList', this.fileList);
                    this.$message.error(`上传图片大小大于${IMG_MAXSIZE}M`);
                    return false;
                }
            }
            if (this.upFileType === 'file') {
                if (upSize > FILE_MAXSIZE) {
                    this.$message.error(`上传文件大小大于${FILE_MAXSIZE}M`);
                    console.log(this.fileList, 'fileList');
                    this.$emit('update:fileListShow', false)
                    return false; 
                }
            }
            if (this.upFileType === 'video') {
                if (upSize > VIDEO_MAXSIZE) {
                    this.$message.error(`上传文件大小大于${VIDEO_MAXSIZE}M`);
                    this.$emit('update:fileListShow', false);
                    return false; 
                }
            }
        },
        // 上传时
        handleProgress(ev, file, fileList) {
            var percent = Math.ceil(ev.percent);
            this.$emit('onProgress', { percent, 'status': percent == 100 ? 'success': 'uploading' });
        },
        // 上传成功的事件
        handleSuccess(response, file) {

            console.log(response, 'res');

            if (response.status === 200) {
                this.curFileUrl = response.content.accessUrl;
                if (!this.isMultiple) {  
                    this.responseJson = {
                        imgUrl: response.content.accessUrl,
                        fileName: response.content.fileName,
                        errorMsg: response.errorMsg
                    };
                } else {
                    this.responseJson = response.content; // 多文件上传的时候取的是一个数组
                }
                
                !this.isMultiple&&(this.upFileType =='image')&&(this.compUploadSuccessFile = true);
                console.log(this.responseJson);
                this.$emit('onSuccess', this.responseJson);
                this.$emit('update:fileListShow', true);
            }
        },
        // 上传错误
        handleError(err) {
            if (err) {
                this.$message('上传出错，请重新上传');
                !this.isMultiple&&(this.upFileType =='image')&&(this.compUploadSuccessFile = false); 
            }
            this.$emit('update:fileListShow', false);
        },
        handleChange(file, fileList) {
            if (file.status == 'success') {
                this.$emit('getFileName', file);
            }
            this.$emit('fileChange', fileList.length);
            if (!this.isMultiple) {
                this.$emit('update:fileList', fileList&&fileList.slice(-1));
            }
            this.dialogImageUrl = '';
        },
        // 删除上传文件
        handleRemove(file) {
            if (file !== null) {
                if (file.status == 'success') {
                    this.curFileUrl = '';
                    this.$emit('remove', file);
                }
            }
            setTimeout(() => {
                !this.isMultiple&&(this.upFileType =='image')&&(this.compUploadSuccessFile = false);     
            }, 490);
        },
        // 获取文件的大小
        _getFileSize(size) {			
            return Math.floor(size/1048576);
        },
        // 获取文件的类型
        _getFileType(type, name) {
            var flag = true;
            if (this.upFileType === 'image') {
                if (!IMG_REGEXP.test(type)) {
                    // image/png
                    this.$message.error('上传图片只能是JPG、PNG、GIF、JPEG格式!');
                    this.$emit('update:fileList', this.fileList);
                    flag = false;
                }
            } else if (this.upFileType === 'file') {
                if (!FILE_REGEXP.test(type)) {
                    this.$emit('update:fileList', this.fileList);
                    this.$message.error('上传文件只能是word、excel、ppt、rar、zip文档类型');
                    flag = false;
                }
            } else if (this.upFileType === 'excel') {
                var off = FILE_EXCEL.indexOf(type);
                var isExcel = '';
                if (name) {
                    isExcel = FILE_EXCEL_REGEXP.test(name);
                }
                if (off < 0 && !isExcel) {
                    flag = false;
                    this.$emit('update:fileList', this.fileList);
                    this.$message.error('上传文件只能是xlsx、xls文档类型');
                }
            } else if (this.upFileType === 'video') {
                
                if (!FILE_VIDEO.test(type)) {
                    this.$emit('update:fileList', this.fileList);
                    this.$message.error('上传视频文件只能是mp4类型');
                    flag = false;
                }
            } else {
                var off = FILE_DOCX.indexOf(type);
                if (off < 0) {
                    flag = false;
                    this.$message.error('上传文件只能是docx、doc文档类型');
                }
            }
            // flag == false && (this.$emit('update:fileListShow', false));
            !this.isMultiple&&(this.upFileType =='image')&&(this.compUploadSuccessFile = false); 
            return flag;
        },
        handleClickUpload() {
            if (!this.isAuto) {
                this.fileList[0].status = 'ready';
            }
            this.$refs.upload.submit();
        },
        // 点击已上传的文件链接时的钩子, 可以通过 file.response 拿到服务端返回数据
        handlePreview(file) {
            if (file&&this.upFileType=='image') {
                console.log(file);
                this.dialogVisible = true;
                this.responseJson.fileName = file.name || '默认文件名';
                this.dialogImageUrl = file.url;
            }
        },
        // 隐藏弹窗预览图片
        hideDialog() {
            console.log(1);
        },
        uploadAgain() {
            this.$nextTick(() => {
                var inputFile = this.$refs.upload.$el.querySelector('input[type=file]');
                inputFile.click();
            })
        }
    },
    mounted() {
        var fileList = this.$refs.upload.$el.querySelector('.el-upload-list--picture-card');

    }
}
</script>
<style lang="scss">
    .bos-file-uplader-component-container {
        overflow: hidden;
        height: auto;
        .up-container {   
            text-align: left;   
        }
        .up-container.border-style {
            border: 1px dashed #c0ccda;
            border-radius: 6px;
        }
    }
    .bos-file-uplader-component-container {
        .el-upload--picture-card {
            position: relative;
            top: 0;
            left: 0;
        }
    }
    .comp-upload-successFile {
        .el-upload--picture-card {
            display: none;
        }
    }
    .upload-again {
        display: inline-block;
        padding: 0 4px;
        color: #ff5e2c; 
        cursor: pointer;
        position: relative;
        top: 0px;
    }
    .user-uploader{
        position: relative;
        height: auto;
    }
    // .visibility-hide{
    //     visibility: hidden;
</style>

